package com.wyj.config;

import org.springframework.context.annotation.Primary;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;

/**
 * TODO: WebApplicationInitializer在SpringServletContainerInitializer中实例化后被调用。
 *      用于引导spring web应用，实现无web.xml配置DispatcherServlet和WebApplicationContext
 *       在Servlet 3.0+环境中实现的接口，以便以编程方式配置ServletContext——与(或可能与)传统的基于web.xml的方法相反。
 *       该SPI的实现将由SpringServletContainerInitializer自动检测，而SpringServletContainerInitializer本身将由任何Servlet 3.0容器自动引导。
 *
 * @author wyj
 * @date 2021/12/4 15:35
 **/
public class MyWebApplicationInitializer implements WebApplicationInitializer {

    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        System.out.println("***************MyWebApplicationInitializer*****************");
        // Load Spring web application configuration
        //通过注解的方式初始化Spring的上下文
        AnnotationConfigWebApplicationContext ac = new AnnotationConfigWebApplicationContext();
        //注册spring的配置类（替代传统项目中xml的configuration）
        ac.register(AppConfig.class);
        ac.refresh();

        // Create and register the DispatcherServlet
        //基于java代码的方式初始化DispatcherServlet
        DispatcherServlet servlet = new DispatcherServlet(ac);
        ServletRegistration.Dynamic registration = servletContext.addServlet("app", servlet);
        registration.setLoadOnStartup(1);
        registration.addMapping("/app/*");
    }
}
